import styles from './index.module.scss';
import { Link } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router-dom';
const NotFound = () => {
  const [count, setCount] = useState(5);

  const timerRef = useRef();

  const history = useHistory();

  useEffect(() => {
    timerRef.current = setInterval(() => {
      // console.log('定时器开始执行');
      setCount(preCount => preCount - 1);
    }, 1000);

    // 组件卸载的时候会执行这个返回的函数，就清理了定时器
    return () => {
      console.log('页面卸载');
      clearInterval(timerRef.current);
    };
  }, []);

  // 监听count值的改变，跳转路由
  useEffect(() => {
    if (count === 0) {
      history.replace('/home');
    }
  }, [count, history]);

  return (
    <div className={styles.root}>
      <h1>对不起，您访问的页面不存在</h1>
      <p>
        将在{count}秒后返回首页，点击立即返回<Link to="/home">首页</Link>
      </p>
    </div>
  );
};

export default NotFound;
